import json
import logging
import threading
import time

import util
from const import cfg, ALL_MSG_TYPES, DEV
from event_handler import friend_msg_handler, group_msg_handler
from msg_handler_impl import moyv_handler
from msg_handler_impl.handler import RedisCommandMsgHandler, LeetCodeMsgHandler, FightingTheLandlordMsgHandler, \
    ChatGPTMsgHandler
from msg_handler_impl.moyv_handler import MoYvMsgHandler
from msg_handler_impl.smart_reply_by_qing_yun_ke_handler import SmartReplyMsgHandler
from msg_handler_impl.travelpolicy_handler import TravelPolicyMsgHandler
from util import mirai_utils

logger = logging.getLogger()

if __name__ == "__main__":
    logger.info("start")
    # 连接到bot
    session = mirai_utils.get_session(cfg, mode=1)
    cfg['session'] = session
    logger.info(cfg['group'])
    groups = cfg['group'].split(',')

    ctx = threading.local()
    ctx.cfg = cfg
    ctx.groups = groups

    single_msg_handler = [
        MoYvMsgHandler(),
        TravelPolicyMsgHandler(),
        SmartReplyMsgHandler(),
        LeetCodeMsgHandler(),
        RedisCommandMsgHandler(),
        FightingTheLandlordMsgHandler(),
        # ChatGPTMsgHandler()
    ]
    friend_msg_handler.HANDLERS.extend(single_msg_handler)
    group_msg_handler.HANDLERS.extend(single_msg_handler)


    def message_handle_core():
        """
        消息处理核心方法
        :return: None
        """
        msgs = mirai_utils.fetch_messages(session)
        if DEV:
            msgs = json.load(open(r"C:\Users\lds\Desktop\testMsgChain.json", encoding="utf-8"))
        if len(msgs) == 0:
            return None

        for msg in msgs:
            logger.info("GET < %s", msg)
            util.msg_record(msg=msg, db=0)
            msg_type = msg.get('type')
            if msg_type not in ALL_MSG_TYPES:
                logger.error("未知的消息类型 [%s]", msg_type)

            if msg_type == 'FriendMessage':
                friend_msg_handler.handle(msg, ctx)
            elif msg_type == 'GroupMessage':
                group_msg_handler.handle(msg, ctx)
        # while True:
        #     text, ind = input("请输入： \n").split()
        #     ind = int(ind)
        #     msg = {
        #         "type": "GroupMessage",
        #         "messageChain": [
        #             {
        #                 "type": "Source",
        #                 "id": 94192,
        #                 "time": 1662631204
        #             },
        #             {
        #                 "type": "Plain",
        #                 "text": text
        #             }
        #         ],
        #         "sender": {
        #             "id": ind,
        #             "memberName": "我是菜鸡",
        #             "group": {
        #                 "id": 725299875
        #             }
        #         }
        #     }
        #     group_msg_handler.handle(msg, ctx)

    logger.info('开始消息处理')
    # 定时任务
    moyv_handler.schedule_task_handle(cfg)
    while True:
        try:
            message_handle_core()
            time.sleep(1)
        except Exception as e:
            logger.error("Error when handle message!", e)


    # for i in single_msg_handler[::-1]:
    #     if hasattr(i, "close"):
    #         i.close()
